package com.spx.wc;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * create by undeRdoG on  2022-04-26  23:10
 * 凡心所向，素履以往，生如逆旅，一苇以航。
 */
public class BatchWordCount {


    public static void main(String[] args) throws Exception {
        // 创建执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        DataSource<String> lineDatasource = env.readTextFile("input/word.txt");

        FlatMapOperator<String, Tuple2<String, Long>> wordAndOne = lineDatasource.flatMap((String line, Collector<Tuple2<String, Long>> out) -> {
            String[] fields = line.split(" ");
            for (String filed : fields) {
                out.collect(Tuple2.of(filed, 1L));
            }
        })
                // 编译后会泛型擦除，这里再主动申明下返回的类型
                .returns(Types.TUPLE(Types.STRING, Types.LONG));

        UnsortedGrouping<Tuple2<String, Long>> wordAndOneGroup = wordAndOne.groupBy(0);

        AggregateOperator<Tuple2<String, Long>> sum = wordAndOneGroup.sum(1);

        sum.print();


    }


}
